package edu.mercer.sse.plainpdf;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;

import com.google.common.base.Function;

import edu.mercer.sse.annotations.Fulfills;
import edu.mercer.sse.configuration.Config;

/**
 * Shutdown an executor service.<p>
 * 
 * Returns false if shutdown timed out while waiting on running task.
 * 
 * @see Function
 */

public class ExecutorServiceTerminationFunction implements
		Function<ExecutorService, Boolean> 
{
	final Integer TIME_OUT = Integer.valueOf( Config.factory()
			.load()
			.get("EXECUTION_TIMEOUT") );

	@Fulfills("Function")
	@Override
	public Boolean apply( final ExecutorService exeService ) 
	{
		try 
		{
			// Wait a while for existing tasks to terminate

			if (! exeService.awaitTermination( TIME_OUT, 
					TimeUnit.MILLISECONDS))
			{
				/* cancel any running tasks */

				exeService.shutdownNow();

			}//if
		 
		} 
		catch( final InterruptedException err ) 
		{		 
			/* (Re-)Cancel if current thread also interrupted */

			exeService.shutdownNow();

			/* Preserve interrupt status */

			Thread.currentThread().interrupt();

			return false;
			
		 }//try
		
		return true;
		
	}//method


}//class
